import 'package:basic_common/common_config.dart';
import 'package:basic_common/common_exports.dart';
import 'package:basic_modle/dr_profile_data.dart';
import 'package:basic_modle/single_user_info.dart';
import 'package:basic_modle/version_data.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:ota_update/ota_update.dart';
import 'package:permission_handler/permission_handler.dart';
import 'app_theme.dart';
import 'global_info.dart';
/* 
 * @description: 公用个人信息数据请求
 * @author: Jane 
 * @date: 2023-09-13 17:07:17
 */
class GlobalGetx extends GetxController {
  final drTagList = [].obs;
  DoctorData? doctorInfo;
  IdentityData? identityInfo;
  final singleImgPath = ''.obs; //单个图片上传返回的Url路径
  final userId = ''.obs; //用户Id
  final doctorNo = ''.obs; //
  final phoneNum = ''.obs; //手机号
  final netWorkState = true.obs; //网络状态

  /// 当前位置信息
  late Position currentPosition = Position(
      longitude: 113.862926,
      latitude: 34.790483,
      timestamp: DateTime.now(),
      accuracy: 40.0,
      altitude: 0.0,
      floor: null,
      heading: 0.0,
      speed: 0.0,
      speedAccuracy: 0.0,
      isMocked: false);

  Map latLng = {}.obs;

  /// 获取医生信息
  getDrProfile() async {
    doctorInfo = null;
    identityInfo = null;
    singleImgPath.value = '';
    userId.value = '';
    doctorNo.value = '';
    phoneNum.value = '';
    HttpData res = await ApiService().drProfile(data: {
      "scene": "get-by-token",
      "sceneDesc": "",
      "searchKey": "Token",
      "searchValue": ""
    });
    if (res.code == 1) {
      if (res.data['doctor'] == null || res.data['identity'] == null) {
        getSIngleUserInfo();
      } else {
        DrProfileData drData = DrProfileData.fromJson(res.data);
        doctorInfo = drData.doctor;
        identityInfo = drData.identity;
        userId.value = doctorInfo!.userId ?? '';
        doctorNo.value = doctorInfo!.doctorNo ?? '';
        print("我的userId=====${doctorInfo!.doctorNick}");
        // verifiedFlag 0 未认证 1 已认证
        // 医生信息为null 代表还未进行实名认证 身份认证 资质认证
        if (doctorInfo!.verifiedFlag == '2') {
          // 审核中
          Future.delayed(Duration.zero, () {
            Get.offAllNamed(AppRoutes.reviewprogress);
          });
        } else if (doctorInfo!.verifiedFlag == '4') {
          // 被拒绝
          Get.offAllNamed(AppRoutes.realname, arguments: {
            "phone": doctorInfo!.phone,
            "id": doctorInfo!.userId
          });
        }

        List list = [
          globalGetx.doctorInfo != null
              ? globalGetx.doctorInfo!.titleName ?? ''
              : "",
          globalGetx.doctorInfo != null
              ? globalGetx.doctorInfo!.dutyName ?? ''
              : ''
        ];
        drTagList.value = List.generate(2, (index) => list[index]);
        update(['doctorInfo']);
      }
      update(['doctorInfo']);
    }
    update(['doctorInfo']);
  }

  /// 记录时间
  int lastTime = 0;

  /// 下载进度
  double downPlan = 0.0;

  /// 是否在下载
  bool isDown = false;

  /// 是否需要更新
  bool isUpdate = false;

  /// 新版本版本号
  String newVersion = '';

// 是否强制更新
  bool isFource = false;

  /// 下载进度
  void downPlanChange(double val) {
    downPlan = val;
    update(['plan']);
  }

  /// 下载状态
  void isDownChange(bool val) {
    isDown = val;
    update(['isupdate']);
  }

  void isUpdateChange(bool val) {
    isUpdate = val;
  }

  void isFourceChange(bool val) {
    isFource = val;
  }

  /// 获取是否有新版本 1 打开APP提示 2 设置版本升级提示
  Future getUpdate(int type) async {
    VersionData res = await globalGetx.getAppVersion();
    isUpdateChange(res.newVersionFlag == 1);
    isFourceChange(res.newVersionInfo?.forceUpdateFlag != 1);
    String localVersion = GlobalInfo.version;
    print("buildNum===本地=--${localVersion}");
    // print("buildNum====${res.newVersionInfo!.versionName}");
    if (res.newVersionInfo!.versionName == localVersion) {
      if (type == 2) {
        ToastUtils.toast("当前已是最新版本，无需更新");
      }
      return;
    }
    showDialog<Null>(
      context: Get.context!, // BuildContext对象
      barrierDismissible: false, // 屏蔽点击对话框外部自动关闭
      builder: (_) => WillPopScope(
          onWillPop: () async {
            int newTime = DateTime.now().millisecondsSinceEpoch;
            int result = newTime - lastTime;
            lastTime = newTime;
            if (result > 1000) {
              ToastUtils.toast("再次返回退出");
            } else {
              SystemNavigator.pop();
            }
            return false;
          },
          child: GetBuilder<GlobalGetx>(
            id: 'isupdate',
            builder: (homeContro) => IndexedStack(
              index: homeContro.isDown ? 1 : 0,
              children: [
                Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Get.theme.primaryColorDark.withOpacity(0.05)),
                    child: Container(
                        width: ScreenHelper.width(315),
                        height: ScreenHelper.width(380),
                        padding: EdgeInsets.only(left: ScreenHelper.width(20.5))
                            .copyWith(
                                top: ScreenHelper.width(44),
                                bottom: ScreenHelper.width(30)),
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage("assets/tab/update_img.png",
                                    package: "basic_common"))),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              alignment: Alignment.topRight,
                              child: GestureDetector(
                                onTap: () {
                                  Get.back();
                                },
                                child: Container(
                                  width: ScreenHelper.width(20),
                                  height: ScreenHelper.width(20),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                        color: Color.fromRGBO(33, 33, 33, 0.8),
                                        width: 1,
                                      ),
                                      borderRadius: BorderRadius.circular(10)),
                                  child: Icon(
                                    Icons.close,
                                    size: ScreenHelper.sp(18),
                                    color: AppTheme.dartTextColor,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              child: Text(
                                '发现新版本！',
                                style: TextStyle(
                                    color: AppTheme.dartTextColor,
                                    fontSize: ScreenHelper.sp(24),
                                    fontWeight: FontWeight.w800),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  top: ScreenHelper.width(20),
                                  bottom: ScreenHelper.width(26)),
                              padding: EdgeInsets.symmetric(
                                  vertical: ScreenHelper.width(4),
                                  horizontal: ScreenHelper.width(5)),
                              decoration: BoxDecoration(
                                  color: AppTheme.primyColor,
                                  borderRadius: BorderRadius.circular(
                                      ScreenHelper.width(20))),
                              child: Text(
                                "v${res.newVersionInfo!.versionName ?? '0.0'}",
                                style: TextStyle(
                                    fontSize: ScreenHelper.sp(14),
                                    color: AppTheme.dartTextColor,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            Expanded(
                              child: Container(
                                margin: EdgeInsets.only(
                                    top: ScreenHelper.width(10)),
                                child: Text(
                                  '''诚邀您体验更好用的新版本，
快来更新吧！''',
                                  style: TextStyle(
                                      color: AppTheme.dartTextColor,
                                      fontSize: ScreenHelper.sp(16),
                                      fontWeight: FontWeight.w400),
                                ),
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                Container(
                                    alignment: Alignment.center,
                                    child: ElevatedButton(
                                      onPressed: () {
                                        if (GetPlatform.isAndroid) {
                                          _updateVersion(
                                              res.newVersionInfo!.url ?? '');
                                        } else if (GetPlatform.isIOS) {
                                          // launch(
                                          //     "https://app.cn/app.html");
                                        }
                                      },
                                      style: ButtonStyle(
                                        backgroundColor:
                                            MaterialStateProperty.resolveWith(
                                                (states) {
                                          return Colors.white;
                                        }),
                                      ),
                                      child: Text('立即升级',
                                          style: TextStyle(
                                              color: AppTheme.primyColor,
                                              fontSize: ScreenHelper.sp(16),
                                              fontWeight: FontWeight.w500)),
                                    )),
                                Container(
                                    alignment: Alignment.center,
                                    child: ElevatedButton(
                                      onPressed: () {
                                        Get.back();
                                      },
                                      style: ButtonStyle(
                                        backgroundColor:
                                            MaterialStateProperty.resolveWith(
                                                (states) {
                                          return Colors.white;
                                        }),
                                      ),
                                      child: Text('暂不体验',
                                          style: TextStyle(
                                              color: AppTheme.dartWeakTextColor,
                                              fontSize: ScreenHelper.sp(16),
                                              fontWeight: FontWeight.w500)),
                                    )),
                              ],
                            )
                          ],
                        ))),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Get.theme.primaryColorDark.withOpacity(0.05)),
                  child: Container(
                    width: ScreenHelper.width(315),
                    height: ScreenHelper.width(252),
                    padding: EdgeInsets.all(ScreenHelper.width(12.5)).copyWith(
                      top: ScreenHelper.width(20),
                    ),
                    decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage("assets/tab/down_bg.png",
                                package: 'basic_common'))),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          margin: EdgeInsets.only(
                            top: ScreenHelper.width(10),
                          ),
                          child: Text('新版本下载中！',
                              style: TextStyle(
                                  color: AppTheme.dartTextColor,
                                  fontSize: ScreenHelper.sp(25),
                                  fontWeight: FontWeight.w500)),
                        ),
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                width: ScreenHelper.width(4),
                                height: 0.5,
                                color: AppTheme.primyColor,
                              ),
                              Container(
                                margin: EdgeInsets.symmetric(
                                    horizontal: 9, vertical: 9),
                                padding: EdgeInsets.symmetric(
                                    vertical: 3, horizontal: 8),
                                decoration: BoxDecoration(
                                    color: Get.theme.primaryColor,
                                    borderRadius: BorderRadius.circular(4)),
                                child: Text(
                                  "NEW",
                                  style: TextStyle(
                                    fontSize: ScreenHelper.sp(14),
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                              Container(
                                width: ScreenHelper.width(41),
                                height: 0.5,
                                color: AppTheme.dartTextColor,
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: ScreenHelper.width(251),
                          margin: EdgeInsets.only(top: ScreenHelper.height(60)),
                          child: GetBuilder<GlobalGetx>(
                            id: 'plan',
                            builder: (homeContro) => Column(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(12.0),
                                  child: LinearProgressIndicator(
                                    backgroundColor: AppTheme.weakTextColor,
                                    valueColor: const AlwaysStoppedAnimation(
                                        AppTheme.primyColor),
                                    minHeight: 6,
                                    value:
                                        (homeContro.downPlan / 100).toDouble(),
                                  ),
                                ),
                                Container(
                                  // color: Colors.red,
                                  margin: EdgeInsets.only(
                                      top: ScreenHelper.width(14)),
                                  child: Text('下载进度${homeContro.downPlan}%',
                                      style: TextStyle(
                                          color: AppTheme.primyColor,
                                          fontSize: ScreenHelper.sp(16),
                                          fontWeight: FontWeight.bold)),
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: ScreenHelper.height(4)),
                          child: Text(
                            "新版本正在努力的更新中，请稍等",
                            style: TextStyle(
                                color: AppTheme.dartTextColor,
                                fontSize: ScreenHelper.sp(14)),
                          ),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          )),
    );
  }

  void _updateVersion(String downLoadurl) async {
    var getup = await checkPermission();
    if (getup) {
      if (GetPlatform.isAndroid) {
        try {
          // destinationFilename 是对下载的apk进行重命名,可以自己定义
          OtaUpdate()
              .execute(downLoadurl, destinationFilename: 'hnxyjapp.apk')
              .listen(
            (OtaEvent event) {
              // print('下载进度====status:${event.status},value:${event.value}');
              switch (event.status) {
                case OtaStatus.DOWNLOADING: // 下载中
                  isDownChange(true);
                  downPlan = double.parse(event.value!);
                  // print("下载百分比==${downPlan}");
                  downPlanChange(downPlan);
                  break;
                case OtaStatus.INSTALLING: //安装中
                  Get.back();
                  break;
                case OtaStatus.PERMISSION_NOT_GRANTED_ERROR: // 权限错误
                  print('更新失败，请稍后再试');
                  ToastUtils.toast("更新失败，请查看安装权限是否开启，稍后再试");
                  break;
                default: // 其他问题
                  break;
              }
            },
          );
        } catch (e) {
          print('更新失败，请稍后再试');
        }
      }
    }
  }

  /// 检查是否有权限，用于安卓
  checkPermission() async {
    PermissionStatus permission = await Permission.storage.status;
    if (permission != PermissionStatus.granted) {
      Map<Permission, PermissionStatus> permissions = await [
        Permission.storage,
      ].request();
      if (permissions[Permission.storage] == PermissionStatus.granted) {
        return true;
      }
    } else {
      return true;
    }
  }

  /// 版本更新
  Future<VersionData> getAppVersion({String? baseUrl}) async {
    VersionData versionData = await ApiService().getVersion(
        data: {"appId": CommonConfig.versionAppId, "versionNo": 0},
        baseUrl: HttpOptions.BASE_SOA_URL);
    // 1 更新 0 不更新
    if (versionData.newVersionFlag == 1) {
      // 更新版本
      return versionData;
    }
    return VersionData();
  }

  /// 获取单个用户信息
  getSIngleUserInfo() async {
    HttpData res = await ApiService().getUserInfoByToken(data: {
      "scene": "get-by-token",
      "sceneDesc": "登录后获取用户个人信息",
      "searchKey": "Token",
      "searchValue": "0"
    });
    if (res.code == 1) {
      SingleUserInfo userInfo = SingleUserInfo.fromJson(res.data);
      String uId = userInfo.userId!;
      String phone = userInfo.phone!;
      if (uId.isEmpty || phone.isEmpty) {
        return ToastUtils.toast("医生ID不能为空");
      }
      Get.offAllNamed(AppRoutes.realname,
          arguments: {"phone": phone, "id": uId});
    }
  }

  /// 获取当前位置
  getCurrentLocation() async {
    if (!GetPlatform.isWindows) {
      currentPosition = (await _determinePosition());
    }
    latLng = {
      'lat': currentPosition.latitude,
      'lng': currentPosition.longitude
    };
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }
    return await Geolocator.getCurrentPosition();
  }

  @override
  void onInit() async {
    await getDrProfile();
    await getCurrentLocation();
    super.onInit();
    connectListener();
  }

  /// 获取联网类型
  void getConnectType() async {
    String _netType = "";
    var connectResult = await (Connectivity().checkConnectivity());
    if (connectResult == ConnectivityResult.mobile) {
      _netType = "4G";
    } else if (connectResult == ConnectivityResult.wifi) {
      _netType = "wifi";
    } else {
      _netType = "未连接";
    }
    print("网络类型===${_netType}");
  }

  /// 判断网络是否连接
  Future<bool> isConnected() async {
    var connectResult = await (Connectivity().checkConnectivity());
    return connectResult != ConnectivityResult.none;
  }

  /// 设置网络切换监听
  connectListener() async {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      print("网络监听====${result}");
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        // ToastUtils.toast("网络已链接");
        netWorkState.value = true;
      } else {
        // ToastUtils.toast("网络已断开");
        netWorkState.value = false;
      }
    });
  }

  
}

final GlobalGetx globalGetx = Get.put<GlobalGetx>(GlobalGetx());
